#define _XOPEN_SOURCE
#include <func.h>
#define SALT_LEN 12
int initDataBase(MYSQL *db);
int getSalt(char salt[]);
int usrRegister(MYSQL *db, char* usr_name, char* passwd);
int usrLogin(MYSQL *db, char* usr_name, char* inputPasswd);
int main(){
    MYSQL *db = mysql_init(NULL);
    initDataBase(db);
    //usrRegister(db, "usr3", "usr3");
    // int ret = usrLogin(db, "usr1", "123");//0
    // printf("ret = %d\n", ret);
    // ret = usrLogin(db, "usr1", "usr1");//-1
    // printf("ret = %d\n", ret);
    // ret = usrLogin(db, "usr5", "123");//0
    // printf("ret = %d\n", ret);
    mysql_close(db);
}

int initDataBase(MYSQL *db){
    char *host = "localhost";
    char *user = "root";
    char *password = "123456";
    char *database = "Cloud";
    MYSQL *ret = mysql_real_connect(db, host, user, password, database, 0, NULL, 0);
    if(ret == NULL){
        printf("Error: %s\n", mysql_error(db));
        exit(-1);
    }
    return 0;
}

int usrRegister(MYSQL *db, char* usr_name, char* passwd){
    char salt[SALT_LEN + 1] = {0};
    getSalt(salt);
    char cryptograph[500] = {0};
    strcpy(cryptograph,crypt(passwd, salt)); //crypt(密码，盐值);
    //insert into UserLoginInformation(user_name, salt, crypt) values(NAME, SALT, CRYPT)
    char sqlCommand[1024] = {0};
    sprintf(sqlCommand, "insert into UserLoginInformation(usr_name, salt, crypt) values('%s', '%s', '%s');", usr_name, salt, cryptograph);
    //puts(sqlCommand);
    int qret = mysql_query(db, sqlCommand);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        return -1;
    }
    return 0;
}

int getSalt(char salt[]){
    int i, flag;
    srand(time(NULL));
    char arr[SALT_LEN - 4];
    for(i = 0; i < SALT_LEN - 4; i++){
        flag = rand()%3;
        switch(flag){
            case 0:
                arr[i] = rand()%26 + 'a';
                break;
            case 1:
                arr[i] = rand()%26 + 'A';
                break;
            case 2:
                arr[i] = rand()%10 + '0';
                break;
        }
    }
    sprintf(salt, "$6$%s$", arr);
}

int usrLogin(MYSQL *db, char* usr_name, char* inputPasswd){
    //select salt, crypt from UserLoginInformation where usr_name = 'usr1';
    char sqlCommand[100] = {0};
    sprintf(sqlCommand, "select salt, crypt from UserLoginInformation where usr_name = '%s';", usr_name);
    int qret = mysql_query(db, sqlCommand);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(db));
        return -1;
    }
    MYSQL_RES *result = mysql_store_result(db);
    char salt[30] = {0};
    char cryptograph[500] = {0};
    MYSQL_ROW row = mysql_fetch_row(result);
    if(row == NULL){
        return -1;
    }
    strcpy(salt, row[0]);
    strcpy(cryptograph, row[1]);
    int ret = strcmp(cryptograph, crypt(inputPasswd, salt));
    if(ret == 0)
        return 0;
    else
        return -1;
}